package com.yy.job.core.dataprocess;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.yy.job.common.enums.JobStatusEnum;
import com.yy.job.constant.JobConstant;
import com.yy.job.core.domain.JobDomain;
import com.yy.job.core.run.worker.ModuleWorker;
import com.yy.job.spring.YYSpringBeanUtils;

/**
 * 状态为(C)的job处理器
 * 
 * @author eleven.li
 *
 */
public class NewJobDataProcess extends BatchJobDataProcess {
	
	private Logger log = LoggerFactory.getLogger(NewJobDataProcess.class);

	public NewJobDataProcess(ModuleWorker moduleWorker) {
		super(moduleWorker);
	}

	@Override
	public void execute(int runCount) {
		log.info("start NewJobDataProcess, moduleWorker name={}", this.moduleWorker.getModuleWorkerName());
		
		try {
			this.performNewJobs(runCount);
		} catch (Exception e) {
			log.info("start NewJobDataProcess failed, moduleWorker name={}", this.moduleWorker.getModuleWorkerName());
			log.error("start NewJobDataProcess failed", e);
		} 
		
		log.info("end NewJobDataProcess, moduleWorker name={}", this.moduleWorker.getModuleWorkerName());
	}
	
	/**
	 * 执行新增的job
	 */
	private void performNewJobs(int runCount) {
		
		List<JobDomain> jobList = null;
		while(true) {
			// 从yy_job表中查询状态为 CREATE("C", "创建")的数据
			jobList = YYSpringBeanUtils.getJobDomainService().listNewJobByPage(
				this.moduleWorker.getProjectCode(),
				this.moduleWorker.getModuleJobConfig().getModuleCode(), JobConstant.PAGE_SIZE);
			log.info("listNewJobByPage, projectCode={}, moduleCode={}, resultJobListSize={}", 
				this.moduleWorker.getProjectCode(),
				this.moduleWorker.getModuleJobConfig().getModuleCode(), jobList.size());
			
			if(CollectionUtils.isEmpty(jobList)) {
				break;
			}
			
			// 随机排序，在分布式下，避免不同机器取到相同的结果集，又按照相同的顺序处理
			//Collections.shuffle(jobList);
			
			// 放到队列中开始处理
			for (JobDomain job : jobList) {
				if (job.getJobStatus() == JobStatusEnum.CREATE && lockJobByVersion(job, runCount) ) {
					job.setRunCount(runCount);
					this.moduleWorker.assignJobToWoker(job);
				}
			}
			
			// 如果最近一次查出来的数量不满足分页数量，则执行完毕退出
			if(jobList.size() < JobConstant.BREAK_PAGE_SIZE) {
				break;
			}
		}
	}
	
}
